﻿CREATE PROCEDURE [maint].[InsertDefragLog]
@DbName [sysname], @TableName [sysname], @IndexName [sysname], @PagesScanned INT, @PagesMoved INT, @PagesRemoved INT, @FragThreshold INT, @LogicalFrag INT, @DefragTime DATETIME, @DefragDuration INT, @OutputDiagnostics BIT=0
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int, @ERROR int
	SET @RC = 0

	IF(@OutputDiagnostics = 1)
		BEGIN
			PRINT OBJECT_NAME(@@PROCID)
			PRINT N'	@DbName = N''' + ISNULL(@DbName,N'NULL') + ''''
			PRINT N'	@TableName = N''' + ISNULL(@TableName,N'NULL') + ''''
			PRINT N'	@IndexName = N''' + ISNULL(@IndexName,N'NULL') + ''''
			PRINT N'	@PagesScanned = N''' + ISNULL(CAST(@PagesScanned AS nvarchar),N'NULL') + ''''
			PRINT N'	@PagesMoved = N''' + ISNULL(CAST(@PagesMoved AS nvarchar),N'NULL') + ''''
			PRINT N'	@PagesRemoved = N''' + ISNULL(CAST(@PagesRemoved AS nvarchar),N'NULL') + ''''
			PRINT N'	@FragThreshold = N''' + ISNULL(CAST(@FragThreshold AS nvarchar),N'NULL') + ''''
			PRINT N'	@LogicalFrag = N''' + ISNULL(CAST(@LogicalFrag AS nvarchar),N'NULL') + ''''
			PRINT N'	@DefragTime = N''' + ISNULL(CAST(@DefragTime AS nvarchar),N'NULL') + ''''
			PRINT N'	@DefragDuration = N''' + ISNULL(CAST(@DefragDuration AS nvarchar),N'NULL') + ''''
		END

	INSERT INTO [maint].[DefragLog](
		[DatabaseName]
		,[TableName]
		,[IndexName]
		,[Pages Scanned]
		,[Pages Moved]
		,[Pages Removed]
		,[FragThreshold]
		,[LogicalFrag]
		,[DefragTime]
		,[DefragDuration]
	) VALUES (
		@DbName
		,@TableName
		,@IndexName
		,@PagesScanned
		,@PagesMoved
		,@PagesRemoved
		,@FragThreshold
		,@LogicalFrag
		,@DefragTime
		,@DefragDuration
	)
	SET @ERROR = @@ERROR
	IF(@ERROR <> 0)
		GOTO ERROR_HANDLER

	GOTO EXIT_PROC

ERROR_HANDLER:
	IF(@RC = 0)
		SET @RC = @ERROR

EXIT_PROC:
	RETURN(@RC)
END